/**
 * @create 2022-05-16
 * @desc auto-track-plugin
 */

const {declare} = require('@babel/helper-plugin-utils');
const importModule = require('@babel/helper-module-imports');

module.exports = declare( (api, options, dirname) => {

    return {
        visitor: {
            Program: { // 从跟节点开始遍历，是否已经引入 track 依赖
                enter(programPath, state) {
                    const trackerPath = options.trackerPath;

                    programPath.traverse({
                        ImportDeclaration(path, state) {
                            const depsPath = path.get('source').node.value;
                            if (depsPath === trackerPath) {
                                const depsNameNode = path.get('specifiers.0');
                                if (depsNameNode.isImportSpecifier()) {
                                    state.trackerImportId = depsNameNode.toString();
                                } else if (depsNameNode.isImportNamespaceSpecifier()) {
                                    state.trackerImportId = depsNameNode.get('local').toString();
                                }
                                path.stop();
                            }
                        }
                    })
                    if (!state.trackerImportId) {
                        state.trackerImportId = importModule.addDefault(programPath, trackerPath, {
                            nameHint: programPath.scope.generateUid('tracker')
                        }).name;
                        state.trackerAST = api.template.statement(`${state.trackerImportId}()`)();

                        // helper-module-imports 不支持 import aaa, {bbb} 的方式，通过 template 插入
                        // const trackerImport = template(`import tracker, {test} from '${trackerPath}'`, {sourceType: "module"})
                        // const lastImport = programPath.get("body").filter(p => p.isImportDeclaration()).pop();
                        // if (lastImport) lastImport.insertAfter(trackerImport());
                    }
                }
            },
            'ClassMethod|ArrowFunctionExpression|FunctionExpression|FunctionDeclaration' (path, state) {
                // const bodyPath = path.get('body'); // body: BlockStatement，数组，里面是各个语句
                // if (bodyPath.isBlockStatement()) { // 存在函数体
                //     bodyPath.node.body.unshift(state.trackerAST);
                // } else { // 箭头函数直接返回
                //     const ast = api.template.statement(`{${state.trackerImportId}();return PREV_BODY;}`)({PREV_BODY: bodyPath.node});
                //     bodyPath.replaceWith(ast);
                // }
            }
        }
    }
})